package com.suxin.lock;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Tang
 * @classname ObjWithLock
 * @description [  ]
 * @date 2022/10/14 14:36
 */
@Slf4j
public class ObjWithLock<T> implements Serializable {

    private T obj = null;

    private final ReentrantReadWriteLock lock;

    public ObjWithLock(T obj) {
        this(obj, new ReentrantReadWriteLock());
    }

    public ObjWithLock(T obj, ReentrantReadWriteLock reentrantReadWriteLock) {
        this.obj = obj;
        this.lock = reentrantReadWriteLock;
    }

    public void handler(ReadLockHandler<T> handler) {
        ReentrantReadWriteLock.ReadLock readLock = readLock();
        try {
            readLock.lock();
            handler.handler(getObj());
        }finally {
            readLock.unlock();
        }
    }

    public void handler(WriteLockHandler<T> handler) {
        ReentrantReadWriteLock.WriteLock writeLock = writeLock();
        try {
            writeLock.lock();
            handler.handler(getObj());
        }finally {
            writeLock.unlock();
        }
    }

    public ReentrantReadWriteLock getLock() {
        return lock;
    }

    public T getObj() {
        return obj;
    }

    public ReentrantReadWriteLock.WriteLock writeLock() {
        return lock.writeLock();
    }

    public ReentrantReadWriteLock.ReadLock readLock() {
        return lock.readLock();
    }
}
